# Alexander F. Gazmararian
# afg2@princeton.edu
rm(list = ls())

# Load packages
library(tidyverse)
library(mapproj)
library(albersusa)#devtools::install_github("hrbrmstr/albersusa")
library(zipcodeR)

# load data
r <- readRDS("data/NatRegQual_Winter21.rds")
state <- albersusa::usa_composite(proj = "longlat")
# retrieve zip code data
r.coord <- reverse_zipcode(r$Zipcode)
# adjust Alaska and Hawaii coordinate
#state@polygons[[50]]  # Alaska
#state@polygons[[51]]  # Hawaii
r.coord <-
  r.coord %>%
  dplyr::mutate(
    lat = ifelse(state == "AK", 25.59189, lat),
    lng = ifelse(state == "AK", -110.9668, lng)
  )
r.coord <-
  r.coord %>%
  dplyr::mutate(
    lat = ifelse(state == "HI", lat + 5.3, lat),
    lng = ifelse(state == "HI", lng + 53, lng)
  )
# pair zip code data with main
r <- subset(r, select = c(Zipcode, sample))
m <- merge(r, r.coord, by.x = "Zipcode", by.y = "zipcode")

# Create realized sample regional figure
reg <-
  m %>%
  dplyr::filter(sample == "Regional") %>%
  dplyr::group_by(Zipcode, lat, lng) %>%
  dplyr::summarise(count = n()) %>%
  dplyr::mutate(count = as.numeric(count))
greys <- grey.colors(22)
reg_map <-
  ggplot() +
  geom_polygon(data = subset(state, name!="Alaska" & name!="Hawaii"), aes(x = long, y = lat, group = group),
               fill = NA, color = "black", size = 0.1) +
  geom_point(data = (reg %>% arrange(count)), aes(x = lng, y = lat, color=count), size=.4) +
  scale_color_steps(low="grey", high = "black", limits = c(0, 22), breaks = seq(0,22,2), oob = scales::squish) +
  coord_map(projection = "lambert", lat = 52, lon = 10) +
  scale_y_continuous(expand=c(0,0)) +
  scale_x_continuous(expand=c(0,0)) +
  labs(x = "", y = "", color = "Responses") +
  theme_void() +
  theme(
    legend.position = "bottom",
    legend.key.width = unit(1.5, "cm"),
    legend.key.height = unit(.4, "cm"),
    plot.margin = margin(0,-20,0,-20)
    )
reg_map

ggsave(
  reg_map,
  filename = "figures/3.1_figure_roosevelt.pdf",
  width = 5,
  height = 3,
  dpi = 300,
  scale = 1.5
)